// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// e [author] rhyme_lph
// s [email]  rhymelph@gmail.com
// Y [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/business_contact_entity.dart';
import 'package:finance_app/src/utils/cash_utils.dart';
import 'package:finance_app/src/utils/language_utils.dart';
import 'package:finance_app/src/widgets/button/filter_button.dart';
import 'package:finance_app/src/widgets/button/normal_down_button.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/chip/normal_chip.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/dash_board/contacts_item.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/dashboard/contact/all_contacts_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';

@RouterMeta(paramName: "allContactsPage")
class AllContactsPage extends StatefulWidget {
  @override
  _AllContactsPageState createState() => _AllContactsPageState();
}

class _AllContactsPageState extends State<AllContactsPage>
    with PagePresenter<AllContactsPage, AllContactsProvider> {
  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
        title: S.current.all_contacts,
      );

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: Column(
          children: [
            AppSpaces.h20,
            SearchInputField(
              controller: provider.searchController,
              focusNode: provider.searchFocusNode,
            ),
            AppSpaces.h20,
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _buildSortContactSelect(),
                FilterButton(
                  onPressed: provider.onShowFilter,
                ),
              ],
            ),
            AppSpaces.h20,
            _buildFilterList(),
            Expanded(
              child: listBuilder<int>(
                selector: (_, __) => __.dataList?.length,
                builder: (BuildContext context, int value, Widget child) =>
                    value == null
                        ? super.buildLoadingWidget
                        : value == 0
                            ? super.buildEmptyWidget
                            : listBuilder<
                                Map<String, List<BusinessContactEntity>>>(
                                selector: (_, __) => Map<String,
                                        List<BusinessContactEntity>>.from(
                                    __.groupMap),
                                builder: (BuildContext context,
                                        Map<String, List<BusinessContactEntity>>
                                            value,
                                        Widget child) =>
                                    value.isEmpty
                                        ? super.buildEmptyWidget
                                        : ListView(
                                            children: _buildContactList(),
                                          ),
                              ),
              ),
            ),
          ],
        ),
      );

  Widget _buildFilterList() {
    return listBuilder<int>(
        builder: (BuildContext context, int value, Widget child) => value == 0
            ? Container()
            : Container(
                height: getDp(30),
                margin: EdgeInsets.only(bottom: getDp(15)),
                alignment: Alignment.centerLeft,
                child: ListView.separated(
                  padding: EdgeInsets.symmetric(
                    horizontal: getDp(10),
                  ),
                  scrollDirection: Axis.horizontal,
                  shrinkWrap: true,
                  itemBuilder: (BuildContext context, int index) =>
                      _buildFilterItem(context, index),
                  itemCount: value,
                  separatorBuilder: (BuildContext context, int index) {
                    return Container(
                      width: getDp(20),
                    );
                  },
                ),
              ),
        selector: (_, __) => __.filterListLength);
  }

  Widget _buildSortContactSelect() {
    return listBuilder<String>(
        builder: (BuildContext context, String value, Widget child) =>
            NormalDownButton(
              title: value,
              onTap: provider.onSelectSortContact,
            ),
        selector: (_, __) => __.currentSelectSortContact);
  }

  Widget _buildFilterItem(BuildContext context, int index) {
    return listBuilder<String>(
        builder: (BuildContext context, String value, Widget child) =>
            NormalChip(
              title: LanguageUtils.translateFilter(value),
              onClose: () => provider.onRemoveFilter(value),
            ),
        selector: (_, __) => __.currentSelectFilterList[index]);
  }

  List<Widget> _buildContactList() {
    List<Widget> child = [];
    for (final item in provider.groupMap.entries) {
      if (item.key.isNotEmpty) {
        child.add(ListHeaderItem(
          title: item.key,
        ));
      }
      child.addAll(item.value.map((e) => ContactsItem(
            onTap: () => provider.onNavContactDetail(e),
            onClickStar: () => provider.onClickStar(e),
            amount: CashUtils.formatCashAmount(
              ((e.receivingAmount ?? 0.0) - (e.payingAmount ?? 0.0)).abs(),
            ),
            isGet: (e.receivingAmount ?? 0.0) - (e.payingAmount ?? 0.0) > 0,
            title: e.name,
            isSelect: e.isFavorite == 1,
            isLastItem: item.value.last == e,
            isOverdue: e.isOverdue == 1,
          )));
    }
    return child;
  }
}
